﻿using System;
using System.Windows;
using System.IO;
using LINQPad.Extensibility.DataContext;

namespace MongoLP
{
	/// <summary>
	/// Interaction logic for ConnectionDialog.xaml
	/// 
	/// NB: pretty much completely lifted from the sample project found 
    ///     here: http://www.linqpad.net/extensibility.aspx
	/// </summary>
	public partial class ConnectionDialog
	{
	    readonly IConnectionInfo _cxInfo;
	    private readonly Properties _connection;

		public ConnectionDialog (IConnectionInfo cxInfo)
		{
			_cxInfo = cxInfo;
			DataContext = cxInfo.CustomTypeInfo;
            _connection = new Properties(cxInfo);
            
            InitializeComponent();
		}

		void BtnOkClick (object sender, RoutedEventArgs e)
		{
            _connection.ConnectionString = this.txtConnectionString.Text;
            _connection.EntityAssemblyPath = this.txtAssemblyPath.Text;
            _connection.EntityInterface = this.txtNameSpace.Text;

            DialogResult = true;
		}

		void BrowseAssembly (object sender, RoutedEventArgs e)
		{
			var dialog = new Microsoft.Win32.OpenFileDialog ()
			{
				Title = "Choose custom assembly",
				DefaultExt = ".dll",
			};

			if (dialog.ShowDialog () == true)
				_cxInfo.CustomTypeInfo.CustomAssemblyPath = dialog.FileName;
		}

	    void ChooseType (object sender, RoutedEventArgs e)
		{
			string assemPath = _cxInfo.CustomTypeInfo.CustomAssemblyPath;
			if (assemPath.Length == 0)
			{
				MessageBox.Show ("First enter a path to an assembly.");
				return;
			}

			if (!File.Exists (assemPath))
			{
				MessageBox.Show ("File '" + assemPath + "' does not exist.");
				return;
			}

			string[] customTypes;
			try
			{
				customTypes = _cxInfo.CustomTypeInfo.GetCustomTypesInAssembly ();
			}
			catch (Exception ex)
			{
				MessageBox.Show ("Error obtaining custom types: " + ex.Message);
				return;
			}
			if (customTypes.Length == 0)
			{
				MessageBox.Show ("There are no public types in that assembly.");  // based on.........
				return;
			}

			string result = (string) LINQPad.Extensibility.DataContext.UI.Dialogs.PickFromList ("Choose Custom Type", customTypes);
			if (result != null) _cxInfo.CustomTypeInfo.CustomTypeName = result;
		}
	}
}
